package org.alis.smallcc.alis.tools.lock.spin;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 *  自旋锁
 *  本类只提供最简单的加锁和解锁 需要升级版的自旋锁请使用
 *  {@link org.alis.smallcc.alis.tools.lock.AlisLock}
 * @author: luochuan     
 * @date: 2020年10月29日 下午4:19:33   
 */
public class SpinLock implements Lock{

	private static final String MESSAGE = "不提供这个操作";
	private AtomicBoolean state = new AtomicBoolean(false);
	
	/**
     * <pre>
     * getAndSet原子操作来判断锁状态并尝试获取锁 
     * 缺点：getAndSet底层使用CAS来实现，一直在修改共享变量的值，会引发缓存一致性流量风暴
     * </pre>
     */
	@Override
	public void lock() {
		while(state.getAndSet(true)) {
			
		}
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		throw new UnsupportedOperationException(MESSAGE);
	}

	@Override
	public boolean tryLock() {
		throw new UnsupportedOperationException(MESSAGE);
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		throw new UnsupportedOperationException(MESSAGE);
	}

	@Override
	public void unlock() {
		state.set(false);
	}

	@Override
	public Condition newCondition() {
		throw new UnsupportedOperationException(MESSAGE);
	}

}
